package com.jeeplus.modules.monitor.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.modules.address.entity.Address;
import com.jeeplus.modules.address.service.AddressService;
import com.jeeplus.modules.comment.entity.Comment;
import com.jeeplus.modules.comment.service.CommentService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.monitor.entity.Task;
import com.jeeplus.modules.product.entity.Product;
import com.jeeplus.modules.product.service.ProductService;
import com.jeeplus.modules.productorder.entity.OrderItem;
import com.jeeplus.modules.productorder.entity.ProductOrder;
import com.jeeplus.modules.productorder.mapper.OrderItemMapper;
import com.jeeplus.modules.productorder.service.ProductOrderService;
import com.jeeplus.modules.productsku.entity.ProductSku;
import com.jeeplus.modules.productsku.service.ProductSkuService;
import com.jeeplus.modules.store.entity.Store;
import com.jeeplus.modules.storescore.entity.StoreScore;
import com.jeeplus.modules.storescore.service.StoreScoreService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.ThreadContext;
import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.*;

/**
 * 取消云店未付款订单
 * @author Administrator
 *
 */
@DisallowConcurrentExecution  
public class CancelXuNiProductOrderTask extends Task {
	private static ProductOrderService productOrderService = SpringContextHolder.getBean(ProductOrderService.class);
	private static MemberService memberService = SpringContextHolder.getBean(MemberService.class);
	private static ProductService productService = SpringContextHolder.getBean(ProductService.class);
	private static ProductSkuService productSkuService = SpringContextHolder.getBean(ProductSkuService.class);
	private static StoreScoreService storeScoreService = SpringContextHolder.getBean(StoreScoreService.class);
	private static CommentService commentService = SpringContextHolder.getBean(CommentService.class);
	private static OrderItemMapper orderItemMapper = SpringContextHolder.getBean(OrderItemMapper.class);

	private static final org.apache.shiro.mgt.SecurityManager MANAGER = SpringContextHolder.getBean(org.apache.shiro.mgt.SecurityManager.class);
	private static Logger logger = LoggerFactory.getLogger(CancelXuNiProductOrderTask.class);
	private static AddressService addressService = SpringContextHolder.getBean(AddressService.class);
	private List<Map<String, Object>> memberListid;

	@Override
	public void run() {
		if (ThreadContext.getSecurityManager() == null) {
			ThreadContext.bind(MANAGER);
		}
		logger.error("每天增加3000个订单！！！");
		int j=0;//定义循环
		while (j<3000){
			Random random = new Random();
			ProductOrder productOrder = new ProductOrder();
			memberListid =memberService.executeSelectSql("SELECT group_concat(id) as uids FROM t_member where is_new_shuadan_member=1");
            if(memberListid==null || memberListid.size() ==0 || memberListid.get(0)==null){
				continue;
			}
			String memberids = memberListid.get(0).get("uids").toString();
			String[] uids = memberids.split(",");
			int uids_len = uids.length;
			if (uids_len <= 0) {
				continue;
			}
			int uid = (int) (Math.random() * uids_len);
			productOrder.setMember(new Member(uids[uid]));
			String[] storeids = new String[]{"14", "19", "124", "122", "245", "23", "15", "48", "255", "29", "30"};
			int storeid = (int) (Math.random() * 9.0D);
			productOrder.setStore(new Store(storeids[storeid]));
			productOrder.setTotalId("ZO2019122611330001");
			productOrder.setState("4");
			String[] payids = new String[]{"1", "2", "3", "4"};
			int payid = (int) (Math.random() * 4.0D);
			productOrder.setPayType(payids[payid]);
			productOrder.setCreateDate(new Date());
			List<Map<String, Object>> addressListid = addressService.executeSelectSql("SELECT group_concat(id) as addresssid FROM t_address");
			if (addressListid == null || addressListid.size() == 0 || addressListid.get(0) == null) {
				continue;
            }
			String addresssid=addressListid.get(0).get("addresssid").toString();
			String[] ids=addresssid.split(",");
			int ids_len=ids.length;
			if(ids_len<=0){
				continue;
			}
			int num = (int)(Math.random() * ids_len);
			Address address = addressService.get(ids[num]);
			if(address==null){
				continue;
			}
			productOrder.setAddress(address.getProvince() + address.getCity() + address.getArea() + address.getDetails());
			productOrder.setPhone(address.getPhone());
			productOrder.setUsername(address.getUsername());
			productOrder.setPayDate(new Date());
			productOrder.setFreight("0.00");
			productOrder.setDiscount("0.00");
			productOrder.setRemarks("");
			List<OrderItem> orderItemList = Lists.newArrayList();
			OrderItem orderItem = new OrderItem();
			List<Map<String, Object>> productListid = productService.executeSelectSql("SELECT group_concat(id) as productids FROM t_product where store_id=" + storeids[storeid]);
			if (productListid == null || productListid.size() == 0 || productListid.get(0) == null) {
				continue;
			}
			String productids = productListid.get(0).get("productids").toString();
			System.out.println(productids);
			String[] productidArrs = productids.split(",");
			System.out.println(productidArrs);
			int productids_len = productidArrs.length;
			System.out.println(productids_len);
			int productid = (int) (Math.random() * productids_len);
			System.out.println(productid);
			System.out.println(productidArrs[productid]);
			Product product = productService.get(productidArrs[productid]);
			if (product == null) {
				continue;
			}
			productOrder.setPrice(product.getPrice());
			productOrder.setPoint(product.getPoint());//铜板
			productOrder.setMoney(product.getPrice());
			productOrder.setAmount(product.getPrice());
			orderItem.setPrice(product.getPrice());
			ProductSku productSku = new ProductSku();
			productSku.setProduct(product);
			ProductSku sku = null;
			int qty=1;
			List<ProductSku> productSkuList = productSkuService.findList(productSku);
			if (productSkuList==null){
				continue;
			}
			Iterator var23 = productSkuList.iterator();

			while(var23.hasNext()) {
				ProductSku productSku2 = (ProductSku)var23.next();
				if (productSku2.getId().equals(((ProductSku)productSkuList.get(0)).getId())) {
					sku = productSku2;
				}
			}

			orderItem.setId("");
			orderItem.setProductId(product.getId());
			orderItem.setSkuId(sku.getId());
			orderItem.setProductCode(product.getCode());
			orderItem.setProductTitle(product.getTitle());
			orderItem.setProductIcon(product.getIcon());
			orderItem.setSkuName(sku.getTitle());
			orderItem.setQty(Integer.valueOf(qty));
			orderItem.setRemarks("");
			orderItem.setPrice((new BigDecimal(sku.getPrice())).multiply(new BigDecimal(qty)).toString());
			orderItem.setPoint((new BigDecimal(sku.getPoint())).multiply(new BigDecimal(qty)).toString());
			orderItem.setDiscount((new BigDecimal(sku.getDiscount())).multiply(new BigDecimal(qty)).toString());
			orderItemList.add(orderItem);
			productOrder.setOrderItemList(orderItemList);
			productOrderService.save(productOrder);
			ProductOrder o = productOrderService.get(productOrder.getId());
			if (o == null) {
				continue;
			}
			//设置商品销量
			int product_qty = product.getSales();
			product_qty = product_qty + qty;
			product.setSales(product_qty);//增加销量
			productService.save(product);
			j++;//增加
			logger.error("增加的" + j + "个订单！！！");
			// 向商家评价表中插入一条数据
			StoreScore ss = new StoreScore();
			ss.setIsNewRecord(true);
			ss.setId(IdGen.uuid());
			Member member = new Member(uids[uid]);
			ss.setMember(member);
			ss.setStore(o.getStore());
			ss.setScore(5);
			ss.setOrderId(o.getId());
			ss.setCreateDate(new Date());
			storeScoreService.save(ss);
			// 向商品评价表中插入一条数据
			OrderItem orderItemid=new OrderItem();
			orderItemid.setOrder(o);
			List<OrderItem> orderItemids=orderItemMapper.findList(orderItemid);
			if (orderItemids==null){
				continue;
			}
			String itemId=orderItemids.get(0).getId();
			JSONObject jsonObject = new JSONObject();
			jsonObject = JSONObject.parseObject("{\"evaluateList\":[{\"productId\":\""+product.getId()+"\",\"itemId\":\""+itemId+"\",\"score\":5,\"content\":\"真好，给个五星好评吧\",\"images\":\"[]\"}]}");
			JSONArray evaluateList =jsonObject.getJSONArray("evaluateList");
			if (evaluateList != null && !evaluateList.isEmpty()) {
				for (int n = 0; n < evaluateList.size(); n++) {
					JSONObject object = evaluateList.getJSONObject(n);
					// 根据订单项ID查询信息
					OrderItem oi = orderItemMapper.get(object.getString("itemId"));
					if (oi==null){
						continue;
					}
					if (oi != null) {
						Comment c1 = new Comment();
						c1.setMember(member);
						c1.setOrderId(o.getId());
						c1.setStore(o.getStore());
						c1.setProduct(new Product(oi.getProductId()));
						c1.setSkuId(oi.getSkuId());
						c1.setProductTitle(oi.getProductTitle());
						c1.setProductIcon(oi.getProductIcon());
						c1.setSkuTitle(oi.getSkuName());
						c1.setPrice(oi.getPrice());
						c1.setQty(oi.getQty());
						c1.setScore(object.getIntValue("score"));
						c1.setContent(object.getString("content"));
						c1.setImages("");
						JSONArray images = object.getJSONArray("images");
						if (images != null && !images.isEmpty()) {
							c1.setImages(StringUtils.join(images, "|"));
						}
						c1.setState("0");
						commentService.save(c1);
					}
				}
			}
			o.setState("4");
			o.setCompleteDate(new Date());
			productOrderService.save(o);
			//程序暂停三秒
			try {
				Thread.currentThread().sleep(3000);

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
